package ntd.util.wx;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import ntd.util.wx.vo.ResUserInfoVo;
import ntd.util.wx.vo.ResVO;

import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

/**
 * 微信支付相关工具类
 */
@Slf4j
public class UtilWxPublic {

    final private static String appid = "wx57d38db1ae2f1c8c"; // appid
    final private static String secret = "cbd692fdbce1fcb00407da7b37a622db"; // appid


    public static ResVO wxLoginPublic(String code) { // 公众号
        final Map<String, Object> params = new TreeMap();
        params.put("appid", appid);
        params.put("secret", secret);
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        final String res = HttpUtil.get("https://api.weixin.qq.com/sns/oauth2/access_token", params);
        log.info("微信获取openId-返回：", res);
        return JSONUtil.toBean(res, ResVO.class);
    }

    public static ResUserInfoVo wxGetUserInfo(String access_token, String openid) { // 公众号
        final Map<String, Object> params = new TreeMap();
        params.put("openid", openid);
        params.put("access_token", access_token);
        params.put("lang", "zh_CN");
        final String res = HttpUtil.get("https://api.weixin.qq.com/sns/userinfo", params);
        log.info("微信获取用户信息-返回：", res);
        return JSONUtil.toBean(res, ResUserInfoVo.class);
    }

    // 统一下单
    public static String unifiedorder(String device_info, String out_trade_no, String total_fee, String openid) {
        return UtilWx.unifiedorder(device_info, out_trade_no, total_fee, openid, appid);
    }

    public static void main(String[] args) {
        final ResVO resVO = wxLoginPublic("071TFn0004D2zK1aTH100yu1uL2TFn0Z");
        Console.log(resVO);
        final ResUserInfoVo resUserInfoVo = wxGetUserInfo(resVO.getAccess_token(), resVO.getOpenid());
        Console.log(resUserInfoVo);

//        final String unifiedorder = unifiedorder(null, "123456789", "88", "");
//        Console.log(unifiedorder);
    }

    /**
     * 获取小程序支付请求参数
     *
     * @param prepay_id
     * @return
     */
    public static Map<String, Object> requestPayment(String prepay_id) {
        final Map<String, Object> params = new TreeMap();
        params.put("appId", appid);
        params.put("timeStamp", new Date().getTime());
        params.put("nonceStr", RandomUtil.randomStringUpper(32));
        params.put("package", prepay_id);
        params.put("signType", "MD5");
        params.put("sign", UtilWx.paySign(params, UtilWx.key));
        log.info("支付请求参数-封装：", params);
        return params;
    }


}
